<script lang="ts" setup>
import { message } from 'ant-design-vue';
import type { PropType } from 'vue';
import { onMounted, ref } from 'vue';
import { useFallBack } from '../useFallBack';
import useUserStore from '@/store/modules/user';
// 返回
const props = defineProps({
  fileDetail: {
    type: Function as PropType<() => void>,
    required: true,
  },
  event: {
    type: String as PropType<string>,
    required: true,
  },
});
// 数据处理
const loading = ref<boolean>(false);
const data = ref<any[]>([]);
const total = ref<number>(0);
const pageSize = ref<number>(10);
const current = ref<number>(1);
const searchKeyword = ref<string>('');
const columns: any = [
  {
    title: '部门',
    dataIndex: 'department',
    key: 'department',
    width: '10%',
    align: 'center',
  },
  {
    title: '主要人员',
    dataIndex: 'mainPersonnel',
    key: 'mainPersonnel',
    width: '10%',
    align: 'center',
  },
  {
    title: '事件名称',
    dataIndex: 'eventName',
    key: 'eventName',
    width: '10%',
    align: 'center',
  },
  {
    title: '活动时间',
    dataIndex: 'eventTime',
    key: 'eventTime',
    width: '20%',
    align: 'center',
  },
  {
    title: '活动地点',
    dataIndex: 'eventLocation',
    key: 'eventLocation',
    width: '20%',
    align: 'center',
  },
  {
    title: '标签',
    dataIndex: 'tags',
    key: 'tags',
    width: '10%',
    align: 'center',
  },
  {
    title: '下载次数',
    dataIndex: 'downloadCount',
    key: 'downloadCount',
    width: '10%',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'lastColumn',
    width: '10%',
    align: 'center',
    fixed: 'right',
  },
];

// 切换显示样式
const value = ref<string>('1');
// 日期格式修改
function formatDate(isoDateString: any) {
  if (!isoDateString || isoDateString === '') {
    return '';
  }
  const date = new Date(isoDateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
// 获取所有图片或视频数据
async function fetchData() {
  data.value = [];
  loading.value = true;
  if (props.event === '无分配文件夹的文件') {
    await getImgByEventPage('', current.value, pageSize.value).then((res: any) => {
      total.value = res.total;
      data.value = res.data.records;
    }).catch(() => {
      message.error('获取数据失败！');
    }).finally(() => {
      loading.value = false;
    });
  }
  else {
    await getImgByEventPage(props.event, current.value, pageSize.value).then((res: any) => {
      total.value = res.total;
      data.value = res.data.records;
    }).catch(() => {
      message.error('获取数据失败！');
    }).finally(() => {
      loading.value = false;
    });
  }
}
async function handleTableChange(pagination: any) {
  pageSize.value = pagination.pageSize;
  current.value = pagination.current;
  if (searchKeyword.value === '') {
    fetchData();
  }
}
onMounted(() => {
  fetchData();
});

// 搜索
async function onSearch(searchKeyword: string) {
  // 输入校验
  if (!searchKeyword || searchKeyword.trim() === '') {
    message.error('搜索关键词不能为空');
    return;
  }
  await searchpicture(searchKeyword).then((response: any) => {
    // 检查响应数据
    if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
      if (props.event === '无分配文件夹的文件') {
        data.value = response.data.filter((event: any) => event.event === null);
      }
      else {
        data.value = response.data.filter((event: any) => event.event === props.event);
      }
      message.success('搜索成功');
    }
    else {
      message.error('没有找到匹配的数据');
    }
  });
}

function back() {
  props.fileDetail();
}

// 预览
const visible = ref<boolean>(false);
const imgItem = ref<any>();
function showModal(record: any) {
  imgItem.value = record;
  visible.value = true;
}

// 判断是否为视频
function isMp4(link: any) {
  return link.toLowerCase().endsWith('.mp4');
}

// 下载图片
async function downImg(imgsrc: string, name: string, imgid: number) {
  // 获取用户信息
  const userStore = useUserStore();
  const tokenname = userStore.userId;
  // 点击下载图片更新数据库
  await clickToDownload(imgid, tokenname.toString());
  fetchData();
  // 下载图片
  if (imgsrc.toLowerCase().endsWith('.mp4')) {
    const fileName = 'video.mp4';
    const a = document.createElement('a');
    a.style.display = 'none';
    document.body.appendChild(a);
    const xhr = new XMLHttpRequest();
    xhr.open('GET', imgsrc, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
      if (xhr.status === 200) {
        const videoBlob = xhr.response;
        const url = window.URL.createObjectURL(videoBlob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
      }
    };
    xhr.send();
  }
  else {
    imgsrc = `${imgsrc}?v=${Math.random()}`;
    const image = new Image();
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = function () {
      const canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      const context = canvas.getContext('2d');
      if (context) {
        context.drawImage(image, 0, 0, image.width, image.height);
      }
      const url = canvas.toDataURL('image/png');
      const a = document.createElement('a');
      const event = new MouseEvent('click');
      a.download = name || 'photo';
      a.href = url;
      a.dispatchEvent(event);
    };
    image.src = imgsrc;
  }
}
</script>

<template>
  <div class="details-c">
    <div class="header">
      <div class="left">
        <a-space>
          <p>文件夹：{{ props.event }}</p>
          <a-radio-group v-model:value="value" name="radioGroup">
            <a-radio value="1">
              列表
            </a-radio>
            <a-radio value="2">
              图
            </a-radio>
          </a-radio-group>
          <a-input-search
            v-model="searchKeyword" v-auth="'e-details-search'" placeholder="请输入关键字" enter-button
            style="width: 15vw;" @search="onSearch"
          />
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-button type="primary" @click="back">
            返回
          </a-button>
        </a-space>
      </div>
    </div>
    <a-table
      v-if="value === '1'" :columns="columns" :data-source="data" row-key="id" class="d-table" :loading="loading"
      :pagination="{ pageSize, showQuickJumper: true, total }" @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="['operation'].includes(column.dataIndex as string)">
          <div class="editable-row-operations">
            <span>
              <a-space>
                <a @click="showModal(record)">预览</a>
                <a @click="downImg(record.link, record.title, record.id)">下载</a>
              </a-space>
            </span>
          </div>
        </template>
      </template>
    </a-table>
    <div v-else class="list-container">
      <a-card v-for="(item, index) in data" :key="index" class="list-item-bordered" hoverable>
        <template #cover>
          <div v-if="isMp4(item.link)">
            <video :src="item.link" style="width: 100%;height: 18vw;" @click="showModal(item)" />
          </div>
          <a-image
            v-else :src="item.link" :alt="item.title" style="width: 100%;height: 18vw;" loading="lazy"
            :fallback="useFallBack().fallback"
          />
        </template>
        <a-card-meta>
          <template #description>
            <a-tooltip placement="right">
              <template #title>
                <p>部门：{{ item.department }}</p>
                <p>主要人员: {{ item.mainPersonnel }}</p>
                <p>活动地点：{{ item.eventLocation }}</p>
                <p>类型：{{ item.eventType }}</p>
              </template>
              <div class="item-description">
                <span class="item-title">事件名称：{{ item.eventName }}</span>
              </div>
              <div class="item-description2">
                <div>活动时间：{{ formatDate(item.eventTime) }}</div>
                <div>标签：{{ item.tags }}</div>
                <div>下载次数：{{ item.downloadCount }}</div>
              </div>
              <div class="item-button">
                <span />
                <a-button
                  style=" width: 4.5vw;height: 2.5vw;font-size: 1vw;line-height: 2vw;text-align: center;"
                  @click="downImg(item.link, item.title, item.id)"
                >
                  下载
                </a-button>
              </div>
            </a-tooltip>
          </template>
        </a-card-meta>
      </a-card>
    </div>
    <a-modal v-model:visible="visible" footer="">
      <div v-if="isMp4(imgItem.link)">
        <video :src="imgItem.link" style="width: 100%;height: 18vw;" controls />
      </div>
      <a-image
        v-else :src="imgItem.link" :alt="imgItem.title" style="width: 100%;height: 18vw;" loading="lazy"
        :fallback="useFallBack().fallback"
      />
    </a-modal>
  </div>
</template>

<style lang="scss" scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 3vw;
  margin-bottom: 0.6vw;

  .pjTitle {
    padding-left: 1vw;
    background: url("@/assets/images/title-left-bg.svg") no-repeat;
  }

  .right {
    display: flex;
    align-items: center;
  }
}

.file {
  flex: 0 0 auto;
  width: calc(20% - 1vw);
  margin-bottom: 1vw;
  text-align: center;
}

.details-c {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

.list-container {
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  gap: 1vw;
  max-width: 100%;
  padding: 0.5vw;
  overflow-y: auto;
}

.list-item-bordered {
  box-sizing: border-box;
  width: calc(25% - 1vw);

  .item-description {
    display: flex;
    align-items: center;
    justify-content: space-between;
    max-width: 100%;
    overflow: hidden;
    line-height: 2vw;

    .item-title {
      font-size: 1.3vw;
      font-weight: 550;
      color: black;
      white-space: nowrap;
    }

    span {
      font-size: 1.3vw;
      white-space: nowrap;
    }
  }

  .item-description2 {
    align-items: center;
    justify-content: space-between;
    max-width: 100%;

    div {
      font-size: 1vw;
      white-space: nowrap;
    }
  }

  .item-button {
    display: flex;

    span {
      flex: 1;
      font-size: 1vw;
      white-space: nowrap;
    }
  }
}
</style>
